package cn.mall.order.utils;

import cn.mall.base.utils.AjaxResult;
import okhttp3.*;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;


public class ConmentUtils {
    public static AjaxResult GetComment(String taskid)//内评论获取
    {

        String guid = java.util.UUID.randomUUID().toString(); // 生成UUID
        long timestamp = System.currentTimeMillis(); // 获取当前时间戳（13位）
        String times = String.valueOf(timestamp);
        String boundary = "------------" + timestamp; // 构建boundary字符串
        // 创建multipart/form-data实体
        MediaType TEXT = MediaType.parse("text/plain; charset=utf-8");
        FormBody.Builder formBuilder = new FormBody.Builder();
        formBuilder
                .add("v_f", "2")
                .add("s", "2799c2af") // 注意：这里第二个参数是空字符串，表示没有值
                .add("max_id_type", "0")
                .add("orifid", "102803$$0")
                .add("s", "2799c2af")
                .add("style", "1")
                .add("count", "1")
                .add("s", "2799c2af")
                .add("skin", "default")
                .add("group_enable", "1")
                .add("is_mix", "1")
                .add("moduleID", "700")
                .add("trim_user", "0")
                .add("fetch_level", "1")
                .add("luicode", "10000002")
                .add("is_reload", "1")
                .add("ft", "0")
                .add("id", taskid) // 使用变量
                .add("android_id", "10c00b597b7b6035")
                .add("v_p", "89")
                .add("max_id", "0")
                .add("request_type", "default")
                .add("oldwm", "2468_1001")
                .add("oriuicode", "10000511_10000002")
                .add("gsid", "_2AkMRPFWgf8NhqwJRmf8UxGvhbIpwyAHEieKnYKR7JRM3HRl-wT9vqnE9tRV6XNyh2LL3XB9wpq1Z37iLEDiQgS621kry")
                .add("wm", "2468_1001")
                .add("uicode", "10000408")
                .add("did", "6d41d0257312add532bec0b4f3033b8862e4141a")
                .add("from", "10B6095010")
                .add("wb_version", "5017")
                .add("ul_ctime", times)
                .add("networktype", "wifi")
                .add("is_append_blogs", "1")
                .add("c", "android")
                .add("ul_hid", guid)
                .add("ua", "Xiaomi-M2007J22C__weibo__11.6.0__android__android7.1.2")
                .add("ignore_inturrpted_error", "true")
                .add("is_encoded", "0")
                .add("is_show_bulletin", "2")
                .add("recommend_page", "1")
                .add("aid", "01A6ChCb9zObyhjkc857CdDLPx1bObZh-z3sdiz5BBLZNyicI.")
                .add("checktoken", "b5f6c49554e24f7d818db0dcd03e1b61")
                .add("ul_sid", guid);

        List<JSONObject> data = userIp();
        Random random = new Random();
        int randomIndex = random.nextInt(data.size());
        System.out.println("---------");
        System.out.println(data.get(randomIndex).toString());
        String proxyHost = null;
        try {
            proxyHost = data.get(randomIndex).get("ip").toString();
            String port = data.get(randomIndex).get("port").toString();
            Integer proxyPort = Integer.parseInt(port);
            String username = data.get(randomIndex).get("username").toString();
            String password = data.get(randomIndex).get("password").toString();
            // 注意：OkHttp 不直接使用 Authenticator.setDefault，而是使用 OkHttpClient.Builder 的 authenticator
            java.net.Authenticator proxyAuthenticator = new java.net.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password.toCharArray());
                }
            };
            Authenticator.setDefault(proxyAuthenticator);
            Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(proxyHost, proxyPort));

            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(30, TimeUnit.SECONDS) // 延长超时时间
                    .writeTimeout(30, TimeUnit.SECONDS)
                    .readTimeout(30, TimeUnit.SECONDS)
                    .proxy(proxy)
                    .build();
            FormBody formBody = formBuilder.build();
            Request request = new Request.Builder()
                    .url("https://api.weibo.cn/2/comments/build_comments?launchid=10000365--x&lang=zh_CN&sflag=1&cum=")
                    .header("Accept", "application/json, text/plain, */*")
                    .post(formBody) // 确保 multipart 是正确的 RequestBody 类型
                    .build();

            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

                // 处理响应
                String result = response.body().string();
//                System.out.println(result);
                try {

                    JSONObject jsonObject = new JSONObject(result);
                    //System.out.println(jsonObject.toString());
                    JSONObject rootComment = jsonObject.getJSONObject("rootComment");
                    String like_counts = rootComment.getString("like_counts");
                    return AjaxResult.me().setResultObj(like_counts);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            catch (IOException e){
                e.printStackTrace();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null; // 如果发生异常或响应为空，则返回null

    }


    public static List<JSONObject> userIp(){
        List<JSONObject> dataList = new ArrayList<>();
        String filePath = "proxy.txt"; // 文本文件路径 D:\weibo_mall\src\main\resources\proxy.txt
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                // 假设每行数据都符合 "IP----端口----username----password----时间" 的格式
                //  \\|
                //
                String[] parts = line.split("----");
                if (parts.length >=4) {
                    String ip = parts[0].trim();
                    String port = parts[1].trim();
                    String username = parts[2].trim();
                    String password = parts[3].trim();
                    // 忽略时间部分
                    // 创建JSONObject并添加到列表中
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("ip", ip);
                    jsonObject.put("port", port);
                    jsonObject.put("username", username);
                    jsonObject.put("password", password); // 注意：在实际应用中，避免存储或传输明文密码
                    dataList.add(jsonObject);
                }
            }
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
        return dataList;
    }

}
